/*************************************************************************
	> File Name: tcp_client.cc
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023/10/05 20:38
 ************************************************************************/

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <cstring>
#include <cerrno>
#include <unistd.h>

const int SIZE = 64;

uint16_t serverport;
std::string serverip;
    
static void usage(std::string proc)
{
    std::cout << "\nUsage:" << proc << " ip port" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3) {
        usage(argv[0]);
        exit(1);
    }
    serverport = atoi(argv[2]);
    serverip = argv[1];
    int serversock = socket(AF_INET, SOCK_STREAM, 0);
    if (serversock < 0) {
        std::cout << "socet error, " << errno << strerror(errno) << std::endl;
        exit(2);
    }
    struct sockaddr_in server;
    memset(&server, 0, sizeof server);
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    if (connect(serversock, (struct sockaddr*)&server, sizeof server)) {
        std::cout << "connect error, " << errno << strerror(errno) << std::endl;
        exit(3);
    }
    std::string message;
    char buffer[SIZE];
    while (1) {
        memset(&buffer, 0, sizeof buffer);
        std::cout << "Please input your question:" << std::endl;
        std::getline(std::cin, message);
        send(serversock, message.c_str(), message.size(), 0);
        ssize_t s = recv(serversock, buffer, sizeof buffer, 0);
        if (s > 0) {
            std::cout << buffer << std::endl;
        } else if (s == 0) {
            std::cout << "server shutdown" << std::endl;
            break;
        } else {
            std::cout << "read error, " << errno << strerror(errno) << std::endl;
            break;
        }
    }
    return 0;
}

